package org.example.service02.controller;

import org.example.service02.entity.User;
import org.example.service02.openFeign.OpenFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.sql.SQLException;
import java.util.List;
import java.util.Random;


@RestController
public class TestController {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/hello")
    public String hello() {
        return "hello service02";
    }

    @Autowired
    private OpenFeignClient openFeignClient;

    @GetMapping("/test01")
    public String test01() {
        return openFeignClient.test01();
    }

    /*@GetMapping("/test01")
    public String test01() {
        return restTemplate.getForObject("http://service01/test01", String.class);

        //另一种写法
        // 获取服务实例列表
        //List<ServiceInstance> instances = discoveryClient.getInstances("service01");
        // 编写一个简易的随机负载均衡算法
        //int size = instances.size();
        //Random random = new Random() ;
        //int instanceIndex = random.nextInt(size);
        //ServiceInstance serviceInstance = instances.get(instanceIndex);
        //restTemplate.getForObject("http://" + serviceInstance.getHost() +":" + serviceInstance.getPort() +"/test01", String.class);
    }*/

    @GetMapping("/test04")
    public String test04() {
        return openFeignClient.test05("jianghui", new Integer[]{1, 2, 3}, List.of("唱", "跳", "RAP"));
    }

    @GetMapping("/test06")
    public String test06() {
        User user = new User();
        user.setId("1");
        user.setName("jianghui");
        user.setAge(18);
        user.setEmail("<EMAIL>");
        return openFeignClient.test06(user);
    }

    @GetMapping("/service02/test07")
    public String test07() throws SQLException {
        return "hello service02";
    }

    @GetMapping("/service02/test08")
    public String test08() throws SQLException {
        return "hello service02";
    }


}
